#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <openssl/des.h>
 
/*
Original code from http://www.codealias.info/technotes/des_encryption_using_openssl_a_simple_example
Small changes were made to convert to Python using swig

There are some problems in Python with the returnings the size can not be the some
so in Python you should adjust the lenght os the strings
so when you do the encriptation ou should do
    A = encr(text, len(text)
and after do:
    A = A[:len(text)]
do the same thing for the deencriptation so you have only the first len(text) characters
*/

char key[]="7Kj3eL5o";
 
char *
Encrypt( char *Key, char *Msg, int size)
{
 
        static char*    Res;
        int             n=0;

        DES_cblock      Key2;
        DES_key_schedule schedule;
 
        Res = ( char * ) malloc( size );
 
        /* Prepare the key for use with DES_cfb64_encrypt */
        memcpy( Key2, Key,8);
        DES_set_odd_parity( &Key2 );
        DES_set_key_checked( &Key2, &schedule );
 
        DES_cfb64_encrypt( ( unsigned char * ) Msg, ( unsigned char * ) Res,
                           size, &schedule, &Key2, &n, DES_ENCRYPT );
 
        return (Res);
}
 
 
char *
Decrypt( char *Key, char *Msg, int size)
{
 
        static char*    Res;
        int             n=0;
 
        DES_cblock      Key2;
        DES_key_schedule schedule;
 
        Res = ( char * ) malloc( size );
 
        /* Prepare the key for use with DES_cfb64_encrypt */
        memcpy( Key2, Key,8);
        DES_set_odd_parity( &Key2 );
        DES_set_key_checked( &Key2, &schedule );
 
        /* Decryption occurs here */
        DES_cfb64_encrypt( ( unsigned char * ) Msg, ( unsigned char * ) Res,
                           size, &schedule, &Key2, &n, DES_DECRYPT );
        return (Res);
 
}

char * encr( char *clear, int t)
{
    char *encrypted;
    encrypted=malloc(t);
    memcpy(encrypted,Encrypt(key,clear,t), t);
    return encrypted;
}

char * decr( char *clear, int t)
{
    char *decrypted;
    decrypted=malloc(t);
    memcpy(decrypted,Decrypt(key,clear,t), t);
    return decrypted;
}


